var Log = require("core_log.js");

/**
 * 请求类型
 */
var Request = {
  Method: {
    Get: 'get',
    Post: 'post',
    Put: 'put',
    Delete: 'delete'
  }
}

/**
 * request
 * 
 * @resolve(res)
 * @reject(res)
 *  res.errorMessage : 自定义错误消息
 */
function request(_method, _scheme, _hostname, _port, _path, _data) {
  const logCallerName = request.name;
  const authority = _hostname + ":" + _port;
  const service = _scheme + "://" + authority;
  const url = service + _path;
  Log.debug(logCallerName, '-->[' + _method + ' ' + url + ']', _data ? _data : "");
  //
  return new Promise(function (resolve, reject) {
      wx.request({
        url: url,
        method: _method,
        header: {
          // 'content-type': 'application/json',
          // 'Accept': 'application/json'
          // 'Cookie': wx.getStorageSync('sessionId')
        },
        data: undefined !== _data ? _data : null,
        success: res => {
          responseHandler(_method, url, res, resolve, reject);
        },
        fail: function (res) {
          const message = "请求出错";
          responseLog(false, logCallerName, message, res, _method, url);
          // 失败回调
          res.errorMessage = message;
          reject(res);
        }
      })
    });
}

/**
 * 响应处理
 */
function responseHandler(_method, url, res, resolve, reject) {
  const logCallerName = "request->"+responseHandler.name;
  // 处理返回状态
  const statusCode = res.statusCode;
  const firstStatus = ('' + statusCode)[0];
  let message = '';
  switch (firstStatus) {
    case '2':
      if (statusCode == 200) {
        responseLog(true, logCallerName, message, res, _method, url);
        // 成功回调
        resolve(res);
        return;
      }
      message = '未知出错';
      break;
    case '4':
      message = '客户端错误';
      break;
    case '5':
      message = '服务器端错误';
      break;
    default:
      message = '未知出错';
  }
  responseLog(false, logCallerName, message, res, _method, url);
  // 失败回调
  res.errorMessage = message;
  reject(res);
}

function responseLog(isOk, _logCallerName, _message, _res, _method, _url) {
  const info = '<--' + _message + '<' + _res.statusCode + '>:[' + _method + ' ' + _url + ']';
  if (isOk){
    Log.debug(_logCallerName, info, _res);
  }else{
    Log.error(_logCallerName, info, _res);
  }
}

module.exports = {
  Request: Request,
  request: request
}
